#include "xlist.h"
#include <stdlib.h>

struct xlist* xlist_build(){
  size_t size=sizeof(struct xlist);
  struct xlist *plist=(struct xlist *)malloc(size);
  return plist;
}

int xlist_release(struct xlist *list){
  struct node *pnode=NULL;

  while(list->head){

    pnode=list->head;
    list->head=pnode->next;
    free(pnode);
    pnode=NULL;
  }
  free(list);
  return 0;
}

int xlist_add(struct xlist *list,void *val){
  struct node *phead=list->head;
  list->size++;

  static size_t size=sizeof(struct node);

  if(!phead){

    struct node *pnode=(struct node *)malloc(size);
    pnode->value=val;
    pnode->next=NULL;

    list->head=pnode;
    return 0;
  }

  for(;phead;phead=phead->next){
    if(phead->value){
      continue;
    }
    phead->value=val;
    return 0;
  }
  struct node *pnode=(struct node *)malloc(size);
  pnode->value=val;
  pnode->next=NULL;


  phead=  list->head;
  list->head=pnode;
  pnode->next=phead;
  return 0;
}

/* compare some one field*/
int xlist_del(struct xlist *list,const void *val,compare func){
  struct node *phead=list->head;

  if(!phead){
    return 0;
  }

  int count=0;
  for(;phead;phead=phead->next){
    if(phead->value==NULL){
      continue;
    }
    int contain=func(phead->value,val);
    if(!contain){
      continue;
    }
    phead->value=NULL;
    list->size--;
    count++;
  }
  return count;
}

int xlist_contain(struct xlist *lst,const void *val,compare func){
struct node *phead=lst->head;

  if(!phead){
    return 0;
  }

  int count=0;
  for(;phead;phead=phead->next){
    if(phead->value==NULL){
      continue;
    }
    
    int contain=func(phead->value,val);
    if(!contain){
      continue;
    }
    count++;
  }
  return count;
}
